package com.itshare.video.common.config.interceptor;

import cn.hutool.core.util.StrUtil;
import com.itshare.video.common.core.constant.enums.ApiInfo;
import com.itshare.video.common.dto.Result;
import com.itshare.video.common.util.JwtAdapter;
import com.itshare.video.common.web.WebUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author lyr
 * @create 2020/9/17 10:32
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // request.setAttribute("unionId","123");
        log.info("uri {}", request.getRequestURI());
        String token = request.getHeader("token");
        log.info("token {}", token);
        if (token == null || StrUtil.isEmpty(token)) {
            //无token, 请求头没有 token
            log.info("请求失败 ");
            WebUtil.renderJson(response, Result.of(ApiInfo.NO_TOKEN));
            return false;
        }
        // request.setAttribute("openId","123");
        // request.setAttribute("id",1L);
        // 获取 请求头的 token信息
        JwtAdapter.TokenResult result = JwtAdapter.getJwtToken(token);
        Claims map = result.getJwtObj();

        //获取 unionID
        // String unionId = (String) map.get(JwtAdapter.UNION_ID);
        //如果 token过期
        if (JwtAdapter.JWTCode.OVERDUE.equals(result.getCode())) {
            //token过期
            WebUtil.renderJson(response, Result.of(ApiInfo.TOKEN_EXPIRED));
            return false;
        }
        // String  id = (String) map.get(JwtAdapter.ID);
        // //如果没有学生信息，说明 还没有注册学号进数据库
        // if(StrUtil.isEmpty(id)) {
        //     //学生还没有注册学号信息
        //     WebUtil.renderJson(response,Result.from("还没有注册学号信息",StatusCode.NEW_USER));
        //     return false;
        // }
        //放行，继续通过
        // Long id = Long.valueOf(strStudentId);


        // String openId = (String) map.get(JwtAdapter.OPEN_ID);
        request.setAttribute("tokenMap", map);
        // request.setAttribute("unionId",unionId);
        // request.setAttribute("openId",openId);
        request.setAttribute("id", map.get("id"));
        request.setAttribute("role", map.get("role"));
        log.info("map {}", map);


        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
